package com.example.huawei.system.config;

import com.example.huawei.system.config.filter.JwtAuthenticationFilter;
import com.example.huawei.system.config.handler.AuthenticationEntryPointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 认证失败处理类
     */
    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                // 设置会话管理策略为无状态（STATELESS）
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .httpBasic().disable() // 禁用HTTP Basic认证
                .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
                // 添加自定义的JwtAuthenticationFilter
                .addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                .antMatchers("/server/login").permitAll() // 开放登录接口，不需要认证
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/v2/*").permitAll()
                .antMatchers("/csrf").permitAll()
                .antMatchers("/").permitAll()
                .antMatchers("/doc.html").permitAll()
                .antMatchers("/server/**").permitAll()
//                .antMatchers("/comment/**").permitAll()
//                .antMatchers("/like/**").permitAll()
//                .antMatchers("/community/**").permitAll()
                .antMatchers("/common/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/pace/**").permitAll()
                .antMatchers("/jwtToken/**").permitAll()
                .antMatchers("/carouselImage/list").permitAll()
//                .antMatchers("/user/**").permitAll()
                .anyRequest().authenticated();
    }
}
